﻿using Mengsk.ProxyDelivery.Domain;
using Mengsk.ProxyDelivery.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Mengsk.ProxyDelivery.UI
{
    /// <summary>
    /// Interaction logic for LoginWindow.xaml
    /// </summary>
    public partial class LoginWindow : Window
    {
        public Operator LoginUser { get; private set; }

        private OperatorService operatorService = ServiceContainer.GetService<OperatorService>();

        public LoginWindow()
        {
            InitializeComponent();
        }

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            string number = this.tbNumber.Text.Trim();
            string password = this.pbPassword.Password.Trim();

            if (string.IsNullOrWhiteSpace(number) || string.IsNullOrEmpty(password))
            {
                MessageBox.Show("用户名或密码不能为空");
                return;
            }

            try
            {
                string serurl = LocalConfigService.GetValue("ServerAddress", "");
                if (string.IsNullOrWhiteSpace(serurl))
                {
                    this.btnSetting_Click(null, null);
                }

                if (string.IsNullOrWhiteSpace(serurl))
                {
                    throw new Exception("没有配置服务器地址");
                }
                ServiceContainer.ServerAddress = serurl;
                Operator user = this.operatorService.Login(number, password);
                if (user == null)
                {
                    MessageBox.Show("用户不存在");
                    return;
                }
                LoginUser = user;
                ServiceContainer.AccessToken = user.Password;
                this.DialogResult = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误");
            }
        }

        private void btnSetting_Click(object sender, RoutedEventArgs e)
        {
            var form = new ServerAddressConfigWindow() { ServerAddress = ServiceContainer.ServerAddress };
            bool? ret = form.ShowDialog();
            if (ret == null || ret.Value == false)
            {
                return;
            }
            ServiceContainer.ServerAddress = form.ServerAddress;
        }
    }
}
